/* Consumer.java
 *
 * Author:	Malcolm Staudacher
 * Date:	Nov 5, 2008
 *
 */

package fhv.itb.ec.jms;

import java.util.Hashtable;
import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Subscriber implements MessageListener {

	public static void main(String[] args) {

		// properties for JNDI
		Hashtable<String, String> jmsProperties = new Hashtable<String, String>();
		jmsProperties.put("java.naming.factory.initial",
				"com.sun.jndi.fscontext.RefFSContextFactory");
		jmsProperties.put("java.naming.provider.url", args[0]);

		try {
			// get JNDI initial context
			InitialContext ictxt = new InitialContext(jmsProperties);

			// get connection factory
			TopicConnectionFactory cf = (TopicConnectionFactory) ictxt
					.lookup("MyTopicConnFactory");

			// get the topic
			Topic topic = (Topic) ictxt.lookup("MyTopic");

			// create connection
			TopicConnection con = cf.createTopicConnection();
			
			// needed to make subscriber durable
			con.setClientID("1st_Durable_Subscriber");

			// create JMS session
			TopicSession sess = con.createTopicSession(false,
					Session.AUTO_ACKNOWLEDGE);
			
			// create message durable consumer (so that messages are durable)
			TopicSubscriber ts = sess.createDurableSubscriber(topic, "test");

			// set this to be an asynchronous message listener
			Subscriber asyncSubscriber = new Subscriber();
			ts.setMessageListener(asyncSubscriber);

			// start connection
			con.start();

			// close connection
			con.close();
			System.out.println("Connection closed by subscriber");

		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


	/**
	 * Retrieves messages from the topic, if any are available.
	 */
	public void onMessage(Message msg) {
		TextMessage tmsg = (TextMessage) msg;

		if (tmsg != null) {
			try {
				System.out.println(tmsg.getText());
			} catch (JMSException e) {
				System.out.println("Could not get message text");
				e.printStackTrace();
			}
		}

	}

}
